package com.cx.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.cx.mall.common.model.order.OrderDetail;
import com.cx.mall.order.mapper.OrderDetailMapper;
import com.cx.mall.order.service.IOrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 订单中所包含的商品 服务实现类
 * </p>
 *
 * @author lyt
 * @since 2025-07-14
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Override
    public List<OrderDetail> listByOrderId(String orderId) {
        LambdaQueryChainWrapper<OrderDetail> wrapper = new LambdaQueryChainWrapper<>(baseMapper);
        List<OrderDetail> list = wrapper.eq(OrderDetail::getOrderId, orderId).list();
        return list;
    }

    @Override
    public List<OrderDetail> listByOrderIds(List<String> orderIds) {
        LambdaQueryChainWrapper<OrderDetail> wrapper = new LambdaQueryChainWrapper<>(baseMapper);
        List<OrderDetail> list = wrapper.in(OrderDetail::getOrderId, orderIds).list();
        return list;
    }

    @Override
    public void removeByOrderId(String id) {
        LambdaUpdateChainWrapper<OrderDetail> updateChainWrapper = new LambdaUpdateChainWrapper<>(baseMapper);
        updateChainWrapper.eq(OrderDetail::getOrderId,id).remove();
    }

    /**
     * 新增订单详情（关联订单ID和商品SKU）
     */
    @Override
    @Transactional
    public boolean saveDetail(String orderId, Long skuId) {
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(orderId);
        detail.setSkuId(skuId);
        // 可补充其他字段（如商品名称、单价等，需从商品服务查询）
        return baseMapper.insert(detail) > 0;
    }

    /**
     * 根据订单ID删除所有关联的详情
     */
    @Override
    @Transactional
    public boolean removeByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        return baseMapper.delete(queryWrapper) > 0;
    }

}
